<?php

class todos extends WikiPlugin
{

	function todos()
	{
		$this->add_macro('todo', 'todo');		
		$this->add_ajax_handler('todo', 'todoajax');
		$this->accumulate('header', 'prototype', 'todoheader_p');
		$this->accumulate('header', 'scriptaculous', 'todoheader_s');
		$this->accumulate('header', 'todo', 'todoheader');
		$this->add_event('after_popup_login', 'todologin');
		$this->add_page('MicroWiki:Todos', 'todohelp');
	}
	
	function todoheader()
	{
		global $rewrite, $wiki, $session;
		
		if(preg_match('/{{todo:.+?}}/i',$wiki->page_rec->body)) {
			$output = '<script type="text/javascript">
			var ajaxurl="' . $rewrite->get_link(array('special'=>'ajax')) . '";
		  var todo_do_kickoff = ' . ($session->is_auth()?'true':'false') . ';
		  </script>';
		  $output .= '<script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'plugins/todos/todo.js')) . '"></script>';
		  return $output;
		}
		return '';
	}
	
	function todoheader_p()
	{
		global $rewrite, $wiki;

		if(preg_match('/{{todo:.+?}}/i',$wiki->page_rec->body)) {
			return '<script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'js/prototype.js')) . '"></script>';
		}
		return '';
	}
	
	function todoheader_s()
	{
		global $rewrite, $wiki;
		
		if(preg_match('/{{todo:.+?}}/i',$wiki->page_rec->body)) {
			return '<script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'js/scriptaculous.js')) . '"></script>';
		}
		return '';
	}
	
	function todo($todoname)
	{
		global $db, $mwconfig, $wiki, $rewrite, $todoidc, $session;
	
		$todoidc++;
		$todoid = 'todo_' . $todoidc;
		
		$content = '<script type="text/javascript" id="' . $todoid . '">wiki_todos.push(["' . $todoid . '", "' . $wiki->page_name . '", "' . $todoname . '"]);</script>';
	
		return $content;
	}
	
	function todoajax() {
	  global $wiki, $mwconfig, $db, $session;
	  
	  if(!$session->is_auth()) return;
	
	  $page = $_POST['page'];
	  $todo = $_POST['todoname'];
	  $pagetext = $wiki->getrawpage($page, $pagerow, false);
	  
	  $regex = '/({{todo:' . $todo . '}})\\s+^(([*#;>][^\\n]+(\\n|$))+)/sim';
	  if(preg_match($regex, $pagetext, $matches)) {
		  $listchar = $matches[2]{0};
		  $replacement = "\\1\n";
		  $ol = '';
		  if(isset($_POST['item'])) {
			  foreach($_POST['item'] as $item) {
			    $replacement .= "{$listchar}{$item}\n";
			    $ol .= "<li>{$listchar}{$item}</li>\n";
			  }
			}
		  $pagetext = preg_replace($regex, $replacement, $pagetext);
		}
		else {
		  $regex = '/({{todo:' . $todo . '}})\\s+/sim';
		  if(preg_match($regex, $pagetext, $matches)) {
			  $listchar = '*';
			  $replacement = "\\1\n";
			  $ol = '';
			  foreach($_POST['item'] as $item) {
			    $replacement .= "{$listchar}{$item}\n";
			    $ol .= "<li>{$listchar}{$item}</li>\n";
			  }
			  $pagetext = preg_replace($regex, $replacement, $pagetext);
			}
			else {
				echo "Couldn't find todo.";
				die();
			}
		}
	  
		$npage = $db->escape($wiki->normalize_str($page));
		$mins = $db->get_var("SELECT ((cast(unix_timestamp(now()) as signed integer) - cast(unix_timestamp(max(postdate)) as signed integer)) / 60) FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}';", 'row');
		$user = $db->get_var("SELECT author FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}' ORDER BY postdate DESC LIMIT 1;");
		if(($mins <= $mwconfig->minoredittime) && ($session->user_id == $user)) {
			$pageid = $db->get_var("SELECT id FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}' ORDER BY postdate DESC LIMIT 1;");
			$pagetext = $db->escape($pagetext);
			$qry = "UPDATE {$mwconfig->db_tableprefix}pages SET body = '{$pagetext}', postdate = NOW() WHERE id = '{$pageid}';";
			$db->query($qry);
		}
		else {
	  	save_page($page, array(
	      'pagecontent' => $pagetext, 
	      'changenote' => 'Todo ' . $todo . ' updated.',
	    ));
	  }
	  echo $session->user_id . "\n" . $pagetext;
	}
	
	function todohelp($page)
	{
		global $wiki;
		return implode("\n", file(dirname(__FILE__).'/todohelp.txt'));
	}
	
	function todologin()
	{
		global $session, $wiki;
	
		$output = '
		if((typeof wiki_todos != "undefined") && (wiki_todos.length > 0) && (!todo_do_kickoff)) {
			if(confirm("Enable todo lists now?")) {
				die = true;
				todo_kickoff();
				Effect.Fade("popuplogin");
			}
		}
		';
		return $output;
	}	
}

?>
